package com.kstech.exccheck.domain.check;

import com.kstech.exccheck.communication.CommandResp;
import com.kstech.exccheck.communication.CommandSender;
import com.kstech.exccheck.config.vo.CheckItemVO;
import com.kstech.exccheck.db.CheckItemDetailDao;
import com.kstech.exccheck.receiver.ReceivedDataKey;
import com.kstech.exccheck.util.AppContext;
import com.kstech.exccheck.view.check.SingleCheckActivity;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * 
 * @author wanghaibin
 * @created 2016-10-23 ����2:50:24
 * @since v1.0
 */
public class SingleCheckReadyTask implements ReceivedDataKey {

//	private static ExecutorService executorService = Executors
//			.newSingleThreadExecutor();

	private static SingleCheckActivity singleCheckActivity;

	public SingleCheckReadyTask(SingleCheckActivity singleCheckActivity) {
		this.singleCheckActivity = singleCheckActivity;
	}

	public void start(CheckItemEntity checkItemEntity) {
//		CheckWorker worker = new CheckWorker(checkItemEntity);
//		executorService.execute(worker);
		// 使用线程池，第二次run方法不执行
		new Thread(new CheckWorker(checkItemEntity)).start();
	}

	private static class CheckWorker implements Runnable {
		private CheckItemEntity checkItemEntity;
		// 获取检查项参数头
		private List<CheckItemParamValueVO> headers;
		// item 配置
		CheckItemVO checkItemVO;

		public CheckWorker(CheckItemEntity checkItemEntity){
			this.checkItemEntity = checkItemEntity;
			headers = AppContext.getModelFile()
					.getCheckItemVO(checkItemEntity.getItemId())
					.getParamNameList();
			// 通过 checkItemEntity 实体对象，找到配置文件中的对应VO
			checkItemVO = AppContext.getModelFile().getCheckItemVO(
					checkItemEntity.getItemId());
		}
		@Override
		public void run() {
			/*<!-- 检测项目使用的提示信息
            ReadyMsg    - 检测准备就绪提示,在发出“准备检测”命令并收到“准备就绪”应答后显示
            NotReadyMsg - 检测准备未就绪（未达检测条件）提示，在发出“准备检测”命令并收到“传感器故障”应答时显示
            AbortMsg    - 检测中止提示，在检测过程中选择“中止检测”发出中止命令且收到“本次测量中止”时显示
            OkMsg       - 检测完成提示，在收到“检测完成”应答时显示
         	-->*/
			// 发送准备检测命令
			CommandSender.sendReadyToCheckCommand(checkItemEntity.getItemId(),
					checkItemEntity.getSumTimes() + 1);
			// 启动计时器，通知UI准备检测
			singleCheckActivity.checkUINoticeForReady("发送准备检测命令",CheckTimer.READY);
			// 准备检测命令响应轮循
			while (true) {
				int totalSec = singleCheckActivity.getCheckTimer()
						.getTotalSec();
				if (totalSec >= (checkItemVO.getReadyTimeout() * 60)) {
					// 发送准备检测命令后，没有对应的应答，已经超时，通知UI线程，程序终止
					singleCheckActivity.checkUINoticeForReady("准备检测命令响应超时，请确认检线连接是否正常",CheckTimer.READY_ERROR);

					// 保存记录，结论，通讯超时(准备阶段，不入库)
					// CheckItemDetailDao.insertDetailAndUpdateItem(CheckItemDetailStatusEnum.CONNECT_TIMEOUT.getCode(),checkItemEntity,headers,checkItemVO);
					return;
				} else {
					String readyToCheckCommandResp = CommandResp
							.getReadyToCheckCommandResp(
									checkItemEntity.getItemId(),
									checkItemEntity.getSumTimes() + 1);
					if ("".equals(readyToCheckCommandResp)) {
						// 还没有响应，继续轮循+
					} else if ("准备就绪".equals(readyToCheckCommandResp)) {
						String readyMsg = checkItemVO.getReadyMsg();
						String content = "";
						if (readyMsg != null && !readyMsg.equals("")) {
							content = AppContext.getResConfig().getResourceVO().getMsg(readyMsg).getContent();
						}
						// 通知UI线程准备就绪，退出循环程序继续执行
						singleCheckActivity.checkUINoticeForReady(content, CheckTimer.READY_FINISH);
						return;
					} else if ("传感器故障".equals(readyToCheckCommandResp)) {
						// 有响应，但是不是准备就绪，则通知UI，传感器故障。程序终止
						String notReadyMsg = checkItemVO.getNotReadyMsg();
						String content = "";
						if (notReadyMsg != null && !notReadyMsg.equals("")) {
							content = AppContext.getResConfig().getResourceVO().getMsg(notReadyMsg).getContent();
						}
						// 保存记录，结论，传感器故障(准备阶段，不入库)
						// CheckItemDetailDao.insertDetailAndUpdateItem(CheckItemDetailStatusEnum.OTHER.getCode(),checkItemEntity,headers,checkItemVO);
						// 通知UI
						singleCheckActivity.checkUINoticeForReady(content, CheckTimer.READY_ERROR);
						return;
					}
				}
				// 间隔100ms，遍历应答区域，是否已经有响应，获取数据后，不将数据应答区置空。与老吴商量
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
